<?php
namespace app\admin\middleware;

use think\facade\Session;
use think\Response;

class AdminAuth
{
    public function handle($request, \Closure $next)
    {
        // 排除登录相关页面
        $excludeActions = ['login', 'dologin', 'captcha'];
        $actionLower = strtolower($request->action());
        
        if (in_array($actionLower, $excludeActions)) {
            return $next($request);
        }
        
        // 调试信息
        $sessionId = session_id();
        $hasAdminUser = Session::has('admin_user');
        $adminUser = Session::get('admin_user');
        
        // 记录调试日志
        logs('AdminAuth调试', [
            'session_id' => $sessionId,
            'has_admin_user' => $hasAdminUser,
            'admin_user' => $adminUser,
            'action' => $request->action(),
            'controller' => $request->controller()
        ]);
        
        // 检查登录状态
        if (!Session::has('admin_user')) {
            if ($request->isAjax()) {
                return json([
                    'code' => 0, 
                    'msg' => '登录已过期，请重新登录', 
                    'url' => '/admin/login'
                ]);
            }
            return redirect('/admin/login');
        }
        
        // 更新最后活动时间
        $adminUser = Session::get('admin_user');
        $adminUser['last_activity'] = time();
        Session::set('admin_user', $adminUser);
        
        return $next($request);
    }
}
